package com.chujian.framework.ws.support.srv;

import com.chujian.framework.util.JsonUs;
import com.chujian.framework.ws.WsMsg;
import com.chujian.framework.ws.IWsRcver;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.BinaryMessage;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;


/**
 * websocket 消息处理器
 */
@Slf4j
public class WsHandler extends TextWebSocketHandler {

    private final IWsRcver wsRcver;

    public WsHandler(IWsRcver wsRcver) {
        this.wsRcver = wsRcver;
    }

    /**
     * 成功建立连接事件
     *
     * @param session
     * @throws Exception
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 保存session
        WsContext.addSession(session);
    }


    /**
     * 接收到文本消息
     *
     * @param session
     * @param message
     * @throws Exception
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload = message.getPayload();
        log.debug("接到消息：{}", payload);

        WsMsg msg = JsonUs.toObj(payload, WsMsg.class);
        msg.addExt("payload", payload);
        wsRcver.onRcv(msg, payload);
    }

    /**
     * 接收到二进制消息
     *
     * @param session
     * @param message
     */
    @Override
    protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) {
        log.info("接到消息二进制消息");
        super.handleBinaryMessage(session, message);
    }

    /**
     * 连接关闭事件
     *
     * @param session
     * @param status
     * @throws Exception
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        String cliId = WsContext.getCliId(session);

        // 移除session
        WsContext.removeSession(session);

        log.warn("关闭连接 cliId={}, code={} , reason={}", cliId, status.getCode(), status.getReason());
    }

}
